package connector;

import cn.dai.pojo2.DbcpUtils;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author ArkD42
 * @file Jdbc
 * @create 2020 - 04 - 24 - 20:47
 */
public class DbcpTest {

    @Test
    public void dbcp1() throws Exception{
        // 创建连接池
        BasicDataSource dataSource = new BasicDataSource();

        // 配置信息
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///jdbc_db?serverTimezone=Asia/Shanghai");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");

        // 连接池管理设置
        //dataSource.setInitialSize(10);  //  初始化池种的连接对象个数
        //dataSource.setMaxIdle(10);      //  最大空闲连接对象个数
        //dataSource.setMinIdle(2);       //  最小空闲连接对象个数

        // 获取连接对象
        Connection connection = dataSource.getConnection();

        System.out.println(connection);
        connection.close();
    }

    @Test
    public void dbcp2() throws Exception{
        String file = DbcpTest.class.getClassLoader().getResource("dbcp.properties").getFile();
        String decode = URLDecoder.decode(file, "utf-8");

        //System.out.println(file);
        //System.out.println(decode);

        InputStream inputStream = new FileInputStream(decode);
        Properties properties = new Properties();
        properties.load(inputStream);
        BasicDataSource dataSource = BasicDataSourceFactory.createDataSource(properties);
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }

    @Test
    public void connect() throws SQLException {
        Connection connection = DbcpUtils.getConnection();
        System.out.println(connection);
        connection.close();
    }
}
